﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Open.Data.Persistence
{
    //Binds the values of a query result row to an item of type T
    public abstract class DataBinder<T>: IDataBinder, IDisposable 
    where T: class, IPersistable, new()
    {
        private T _item;
        private IQuery _query;
        private QueryDataAdapter _adapter;
        private bool _hasChanged;
        private Formatter _formatter;

        public DataBinder(IQuery query)
        {
            if (query == null) throw new ArgumentNullException();
            _query = query;
        }

        public IQuery Query
        {
            get
            {
                return _query;
            }
            set
            {
                _query = value;
            }
        }

        public QueryDataAdapter DataAdapter
        {
            get
            {
                return _adapter;
            }
            set
            {
                _adapter = value;
            }
        }

        public Formatter Formatter
        {
            get
            {
                return _formatter;
            }
            set
            {
                _formatter = value;
            }
        }

        public T Item
        {
            get
            {
                return _item;
            }
            set
            {
                _item = value;
            }
        }

        public bool HasChanged
        {
            get
            {
                return _hasChanged;
            }
            set
            {
                _hasChanged = value;
            }
        }

        public void CreateItem()
        {
            _item = new T();
        }

        public IPersistable GetItem()
        {
            return _item;
        }

        public virtual void ClearItem()
        {
            _item = null;
        }

        public void Dispose()
        {
            if (DataAdapter != null) DataAdapter.Dispose();
        }

        public abstract bool Read();
        public abstract void Bind();
        public abstract List<T> ToList();
    }
}
